package com.sky.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.constant.CacheConstant;
import com.sky.constant.PreConstant;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.IDishFlavorService;
import com.sky.service.IDishService;
import com.sky.service.IShoppingCartService;
import com.sky.utils.ThreadLocalUtil;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController("/userDishController")
@RequestMapping("/user/dish")
public class DishController {
    @Autowired
    private IDishService iDishService;
    @Autowired
    private IDishFlavorService iDishFlavorService;
    @Autowired
    private IShoppingCartService iShoppingCartService;

    @GetMapping("/list")
    @Cacheable(cacheNames = CacheConstant.DISH_CACHE,key = "#dto.categoryId")
    public Result list(DishDTO dto){
        //走到这里说明不存在查数据，则查数据库，并加入缓存
        LambdaQueryWrapper<Dish> lqw =new LambdaQueryWrapper<>();
        lqw.eq(dto.getCategoryId()!=null,Dish::getCategoryId,dto.getCategoryId());
        List<Dish> list = iDishService.list(lqw);
        //缓存菜品   key  -value      =>    dish_categoryId   - {list}
//        redisTemplate.opsForValue().set(PreConstant.PRE_DISH +dto.getCategoryId(),list);
        //应该传vo
        List<DishVO> voList =new ArrayList<>();
        list.forEach(dish->{
            LambdaQueryWrapper<DishFlavor> lqw1 =new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavors = iDishFlavorService.list(lqw1);
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(dishFlavors);
            voList.add(dishVO);
        });
        return Result.success(voList);
    }
}
